package com.hd.manager.shiro;


import com.hd.appcommon.entity.Teacher;
import com.hd.appcommon.entity.User;
import com.hd.hdxgddcommon.utils.StringUtils;
import com.hd.manager.exception.MyAuthException;
import com.hd.manager.shiro.sevice.IShiroAdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Administrator on 2018/10/26.
 * Description :  实现 AuthorizingRealm
 */

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IShiroAdminService shiroAdminService;

    public MyRealm() {

    }

    public MyRealm(CacheManager cacheManager) {
        super(cacheManager);
    }

    /**
     * 用户认证
     *
     * @param authenticationToken 用户账号密码token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        if (token == null) throw new MyAuthException("请输入账号密码!");
        String account = token.getUsername();
        String password = new String(token.getPassword());

        if (StringUtils.isNotBlank(account, password)) {
            String encryptPassword =  ShiroUtils.getEncryptPassword(account, password);
            User user = shiroAdminService.getByAccount(account, encryptPassword);
            if (null == user.getType()||user.getType()!=2) {
                throw new MyAuthException("账号密码不正确");
            }
            return new SimpleAuthenticationInfo(user, password, getName());
        }
        throw new MyAuthException("账号密码不能为空!");
    }

    /**
     * 获取当前登录用户的角色权限信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //添加角色
//        List<Role> roles = TokenManager.getTokenRoles();
//        roles.forEach(role -> authorizationInfo.addRole(role.getRoleName()));
//        //添加权限
//        List<Privilege> privileges = TokenManager.getTokenPrivileges();
//        privileges.forEach(privilege -> authorizationInfo.addStringPermission(privilege.getPrivilegeKey()));
        return authorizationInfo;
    }

}
